
/**************************************************
* Name : Hanggoro Adi H
* Nama file : ServiceJdbc.java
* Tanggal pembuatan : Nov 27, 2012
* Deskripsi : 
***************************************************/
package net.mygoro.project.service;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import net.mygoro.project.dao.PersonDaoJdbc;
import net.mygoro.project.model.Person;



/**
 *
 * @author support
 */
public class ServiceJdbc {
    
    private PersonDaoJdbc personDao;
    private Connection connection;
    
    public void setDateSource(DataSource dataSource){
        try{
            connection = dataSource.getConnection();
            personDao = new PersonDaoJdbc();
            personDao.setConnection(connection);
        }catch(SQLException ex){
            ex.printStackTrace();
        }
    }
    
    public Person save(Person person) throws SQLException{
        try{
            connection.setAutoCommit(false);
            personDao.save(person);
            connection.commit();
            connection.setAutoCommit(true);
        }catch (SQLException ex){
            try{
                connection.rollback();
            }catch(SQLException e){
                ex.printStackTrace();
            }
        }
        return person;
    }
    
    public Person delete(Person person){
        try{
            connection.setAutoCommit(false);
            personDao.save(person);
            connection.commit();
            connection.setAutoCommit(true);
        }catch(SQLException ex){
            try{
                connection.rollback();
            }catch(SQLException e){
                ex.printStackTrace();
            }
        }
        return person;
    }
    
    public Person getPerson(Long id){
        try {
            return personDao.getById(id);
        }catch(SQLException ex){
            ex.printStackTrace();
        }
        return null;
    }
    public List<Person> getPersons(){
        try{
            return personDao.getAll();
        }catch(SQLException ex){
            ex.printStackTrace();
        }
        return new ArrayList<Person>();
    }

}
